package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OSSConfig;
import net.xdclass.service.FileService;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author guangyang
 * @since 2023-01-20
 **/
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {
        //获取相关配置
        String bucketname = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //JDK8的日期格式
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //拼装路径，oss中的路径  2023/01/20 / dslkangkajg.jpg
        String floder = formatter.format(now);

        String fileName= CommonUtil.generateUUID();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName="user/"+floder+"/"+fileName+substring;

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketname, newFileName, file.getInputStream());
            if(putObjectResult!=null){
                String imgUrl="https://"+bucketname+"."+endpoint+"/"+newFileName;
                return imgUrl;

            }
        } catch (IOException e) {
            log.error("文件上传失败:{}",e.getMessage(),e);
        }finally {
            ossClient.shutdown();
        }


        return null;
    }
}
